from flask import Blueprint, jsonify, request, current_app
from applications.models.frontend import Order, db, User
from applications.view.system.decorators import jwt_required
from datetime import datetime

# 创建订单管理蓝图
order_bp = Blueprint('order', __name__, url_prefix='/system/order-management')


# ====================== 辅助函数 ======================
def get_order_status_text(status):
    """
    获取订单状态文本
    :param status: 状态码
    :return: 状态文本
    """
    status_map = {
        0: '待支付',
        1: '已支付',
        2: '已发货',
        3: '已完成',
        4: '已取消',
    }
    return status_map.get(status, '未知状态')


# 获取订单列表
@order_bp.route('/orders', methods=['GET'])
@jwt_required()
def get_orders():
    """
    获取订单列表
    支持参数过滤: user_id, status, start_date, end_date
    支持分页: page, per_page
    """
    try:
        # 获取查询参数
        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('per_page', 10))
        user_id = request.args.get('user_id')
        status = request.args.get('status')
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')

        # 构建查询，并关联User以获取用户名
        query = Order.query.join(User, Order.user_id == User.id)

        # 应用过滤条件
        if user_id:
            query = query.filter(Order.user_id == int(user_id))
        if status is not None and status != '':
            query = query.filter(Order.status == int(status))
        if start_date:
            start_datetime = datetime.strptime(f'{start_date} 00:00:00', '%Y-%m-%d %H:%M:%S')
            query = query.filter(Order.order_time >= start_datetime)
        if end_date:
            end_datetime = datetime.strptime(f'{end_date} 23:59:59', '%Y-%m-%d %H:%M:%S')
            query = query.filter(Order.order_time <= end_datetime)

        # 执行分页查询
        pagination = query.order_by(Order.order_time.desc()).paginate(page=page, per_page=per_page)

        # 构建响应数据
        orders_data = [{
            'id': order.id,
            'order_no': order.order_no,
            'user_id': order.user_id,
            'username': order.user.username,
            'total_amount': float(order.total_amount),  # Decimal转为float
            'status': order.status,
            'status_text': get_order_status_text(order.status),
            'admin_status': order.admin_status,
            'recipient_name': order.recipient_name,
            'phone': order.phone,
            'address': order.address,
            'order_time': order.order_time.strftime('%Y-%m-%d %H:%M:%S') if order.order_time else None,
            'payment_time': order.payment_time.strftime('%Y-%m-%d %H:%M:%S') if order.payment_time else None,
        } for order in pagination.items]

        return jsonify({
            'code': 200,
            'message': '获取订单列表成功',
            'rows': orders_data,
            'total': pagination.total,
        })
    except Exception as e:
        current_app.logger.error(f'获取订单列表失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'获取订单列表失败: {str(e)}'}), 500


# 管理订单（获取、更新、删除）
@order_bp.route('/<int:order_id>', methods=['GET', 'PUT', 'DELETE'])
@jwt_required()
def manage_order(order_id):
    """
    管理单个订单：获取详情、更新状态、删除订单
    :param order_id: 订单ID
    """
    order = Order.query.get_or_404(order_id)

    if request.method == 'GET':
        try:
            # 获取订单商品
            order_items = [{
                'id': item.id,
                'product_id': item.product_id,
                'product_name': item.product.name if item.product else None,
                'product_image': item.product.main_image if item.product else None,
                'quantity': item.quantity,
                'price': item.price,
            } for item in order.order_items]

            # 构建订单详情数据
            order_data = {
                'id': order.id,
                'order_no': order.order_no,
                'user_id': order.user_id,
                'username': order.user.username,
                'total_amount': float(order.total_amount),
                'status': order.status,
                'status_text': get_order_status_text(order.status),
                'admin_status': order.admin_status,
                'recipient_name': order.recipient_name,
                'phone': order.phone,
                'address': order.address,
                'order_time': order.order_time.strftime('%Y-%m-%d %H:%M:%S') if order.order_time else None,
                'payment_time': order.payment_time.strftime('%Y-%m-%d %H:%M:%S') if order.payment_time else None,
                'items': order_items
            }
            return jsonify({'code': 200, 'message': '获取订单详情成功', 'data': order_data})
        except Exception as e:
            current_app.logger.error(f'获取订单详情失败: {str(e)}')
            return jsonify({'code': 500, 'message': f'获取订单详情失败: {str(e)}'}), 500

    elif request.method == 'PUT':
        try:
            data = request.json
            # 更新订单状态
            status = data.get('status')
            if status is not None and 0 <= status <= 4:
                now = datetime.now()
                if status == 1 and order.status == 0:  # 待支付 -> 已支付
                    order.payment_time = now
                order.status = status

            # 更新管理员处理状态
            admin_status = data.get('admin_status')
            if admin_status:
                order.admin_status = admin_status

            db.session.commit()
            return jsonify({'code': 200, 'message': '更新订单成功'})
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f'更新订单失败: {str(e)}')
            return jsonify({'code': 500, 'message': f'更新订单失败: {str(e)}'}), 500

    elif request.method == 'DELETE':
        try:
            db.session.delete(order)
            db.session.commit()
            return jsonify({'code': 200, 'msg': '订单删除成功！'})
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f'删除订单失败: {str(e)}')
            return jsonify({'code': 500, 'msg': '订单删除失败', 'error': str(e)}), 500


# 注册蓝图
def register_order_bp(app):
    app.register_blueprint(order_bp)
